require "proto/expedition/message/ReqSynExpeditionMessage"
require "proto/expedition/message/ReqSelectRegionMessage"
require "proto/expedition/message/ReqGetAwardMessage"
require "proto/expedition/message/ReqResetExpeditionMessage"
require "proto/expedition/message/ReqUseBuffMessage"
require "proto/expedition/message/ReqExpeditionBossMessage"
require "proto/expedition/message/ReqExpeditionSweepMessage"
require "proto/expedition/message/ReqExpeditionQuickSweepMessage"
ExpeditionHandler = {}
local t = ExpeditionHandler
--region req
local ignoreUI = false
local chooseBuffIndex = 0
--请求远征
function t.ReqSynExpedition(ignoreui)
    local m = ReqSynExpeditionMessage.New()
    ignoreUI = ignoreui
    sendReqMessage(m)
end
--请求选择区域
function t.ReqSelectRegion(id,idx)
    ignoreUI = false
    local m = ReqSelectRegionMessage.New()
    m.regionId = id
    m.sendBuff = idx or 0
    sendReqMessage(m)
end
--请求领取奖励
function t.ReqGetAward(id)
    local m = ReqGetAwardMessage.New()
    m.stageId = id
    sendReqMessage(m)
end
--请求重置
function t.ReqResetExpedition()
    local m = ReqResetExpeditionMessage.New()
    sendReqMessage(m)
end
--请求使用buff卡
function t.ReqUseBuff(stageId,index)
    local m = ReqUseBuffMessage.New()
    m.stageId = stageId
    m.buffIndex = index;
    chooseBuffIndex = index
    sendReqMessage(m)
end
function t.ReqExpeditionBoss(stageId,formation)
    local m = ReqExpeditionBossMessage.New()
    m.stageId = stageId
    m.formation = formation
    sendReqMessage(m)
end
function t.ReqExpeditionSweep()
    local m = ReqExpeditionSweepMessage.New()
    sendReqMessage(m)
end
function t.ReqExpeditionQuickSweep(selectId)
    local m = ReqExpeditionQuickSweepMessage.New()
    m.regionId = selectId
    sendReqMessage(m)
end
--endregion req

--region res
--返回远征大地图
function t.ResSynExpeditionHandler(msg)
    for k,v in pairs(msg.regionList) do
        logicMgr.ExpeditionMgr.AddMapInfo(v)
    end
    logicMgr.ExpeditionMgr.isMapView = true
    logicMgr.ExpeditionMgr.MapFistWardInfo(msg.gotAreaRewards)
    logicMgr.ExpeditionMgr.endTime = msg.endTime
    logicMgr.ExpeditionMgr.ClearStage()
    logicMgr.ExpeditionMgr.ClearHeroList()
    logicMgr.ExpeditionMgr.SetCanSweep(msg.canSweep)
    logicMgr.ExpeditionMgr.SetSweepCount(msg.useTicketNum)
    logicMgr.ExpeditionMgr.SetResetType(msg.resetType)
    if logicMgr.ExpeditionMgr.GetResetType() == 3 then
        logicMgr.ExpeditionMgr.SetRedPoint()
    else
        logicMgr.ExpeditionMgr.SetRedPoint(true)
    end
    logicMgr.ExpeditionMgr.passRegionToday = {}
    logicMgr.ExpeditionMgr.strength = msg.power
    logicMgr.ExpeditionMgr.srvCDTime = msg.remainTime
    logicMgr.ExpeditionMgr.nextStrengthAddTime = HelperFunc.GetServerTime() + G.dataTable["t_global"][tostring(595)]["f_string_value"][2] - msg.remainTime
    logicMgr.ExpeditionMgr.maxStrength = msg.powerMax
    for k,v in pairs(msg.passRegionToday) do
        logicMgr.ExpeditionMgr.passRegionToday[v] = true
    end

    FireEvent(Config.EventType.ExpeditionDataRefresh)
    if not ignoreUI then
        ignoreUI = false
        t.closeAllUI()
        closeUI(PanelNames.UIBottom)
        if msg.selectState == 1 then --map地图
            if logicMgr.ExpeditionMgr.endTime < HelperFunc.GetServerTime() then -- 时间过期重新获取
                ExpeditionHandler.ReqResetExpedition()
                return
            end
            showUI(PanelNames.UIExpeditionMapView)
        elseif msg.selectState == 2 or msg.selectState == 3 then--重置
            closeUI(PanelResNames.UIExpeditionStageView)
            showUI(PanelNames.UIExpeditionMapView)
        end
    end
    ignoreUI = false
end
--返回选择区域信息
function t.ResSelectRegionHandler(msg)
    logicMgr.ExpeditionMgr.ClearStage()
    logicMgr.ExpeditionMgr.SetRedPoint()
    local curStage = 0
    for k,v in pairs(msg.stageList) do
        logicMgr.ExpeditionMgr.AddStageInfo(v)
        if v.state == 0 then
            curStage = v.stageId
        elseif v.state == 1 then
            curStage = math.max(curStage,v.stageId + 1)
        end
    end
    logicMgr.ExpeditionMgr.SetCurStageId(math.min(curStage,12))
    for k,v in pairs(msg.buffList) do
        logicMgr.ExpeditionMgr.AddStageBuff(v)
    end
    if logicMgr.ExpeditionMgr.IsCompleteAllStage() then
        logicMgr.ExpeditionMgr.isStartExpedition = false
    else
        logicMgr.ExpeditionMgr.isStartExpedition = true
    end
    logicMgr.ExpeditionMgr.isMapView = false
    logicMgr.ExpeditionMgr.resetCount = msg.resetCount
    logicMgr.ExpeditionMgr.endTime = msg.endTime or 0
    logicMgr.ExpeditionMgr.mapId = msg.regionId
    logicMgr.ExpeditionMgr.mapDifficulty = msg.difficulty
    logicMgr.ExpeditionMgr.mapBuffId = msg.regionBuffId
    logicMgr.ExpeditionMgr.missCount = msg.missCount or 0
    if #msg.buffIdList >0 then
        logicMgr.ExpeditionMgr.AddShowBuff(msg.buffIdList)
    end
    logicMgr.ExpeditionMgr.SetCanSweep(msg.canSweep)
    logicMgr.ExpeditionMgr.SetSweepCount(msg.useTicketNum)
    logicMgr.ExpeditionMgr.strength = msg.power
    logicMgr.ExpeditionMgr.srvCDTime = msg.remainTime
    logicMgr.ExpeditionMgr.nextStrengthAddTime = HelperFunc.GetServerTime() + G.dataTable["t_global"][tostring(595)]["f_string_value"][2] - msg.remainTime
    logicMgr.ExpeditionMgr.maxStrength = msg.powerMax
    local f = {}
    for k,v in pairs(msg.formation) do
        local id = tostring(v)
        if not logicMgr.ExpeditionMgr.IsDead(id) then
            f[k] = id
        end
    end
    logicMgr.FormationManager.SetFormation(EnumConst.FormationType.Expedition,f)

    FireEvent(Config.EventType.ExpeditionDataRefresh)
    FireEvent(Config.EventType.ExpeditionSweepRefresh)

    if not ignoreUI then
        ignoreUI = false
        if logicMgr.ExpeditionMgr.IsCompleteAllStage() then
            if ExpeditionMgr.resetCount == 1 then
                local info = ExpeditionMgr.GetStageInfo(ExpeditionMgr.GetCurStageId())
                if ExpeditionMgr.needShowLastTip then
                    ExpeditionMgr.needShowLastTip = false
                    UIShowManager.ShowExpeditionFinalBossReward(info.items)
                end
                ExpeditionHandler.ReqResetExpedition()
                return
            end
        end
        t.closeAllUI()
        showUI(PanelNames.UIExpeditionStageView,true)
        closeUI(PanelResNames.UIExpeditionMapView)
    end
    ignoreUI = false
    --远征开启埋点
    local _expeditionDic = {}
    _expeditionDic.map_id = tostring(msg.regionId)
    _expeditionDic.map_buff_id = tostring(msg.regionBuffId)
    _expeditionDic.target = 1
    _expeditionDic.expedition_end_time = TimeFormateByMs(logicMgr.ExpeditionMgr.endTime * 1000)
    -- _expeditionDic.hero_level = -1
    -- _expeditionDic.hero_quality = -1
    TAManager.TrackByDictionary("expedition_open",_expeditionDic)

    --状态是使用远征券切返回成功且selectstate为3（用券返回），则请求快速扫荡
    if msg.state == 0 and logicMgr.ExpeditionMgr.GetResetType() == 3 then
        logicMgr.ExpeditionMgr.SetResetType(1)
        --t.ReqExpeditionQuickSweep();
    end

    logicMgr.TATrackCollect.Track_Expedition()
end
function t.closeAllUI()
    closeUI(PanelNames.UICity);
    closeUI(PanelNames.UIAdventureMain,true);
    closeUI(PanelNames.UICharactorMain);
    closeUI(PanelNames.UIBattle);
    closeUI(PanelNames.UIBattleMain);
    closeUI(PanelNames.UIChatPanel);
    closeUI(PanelNames.UIDraw);
    closeUI(PanelNames.UIFuncMenu);
    closeUI(PanelResNames.UIHeadMenu)
end
function t.ResGetAwardHandler(msg)
    if msg.state == 0 then
        logicMgr.ExpeditionMgr.SetStageAwardState(msg.stageId,1,msg.buffId)
        logicMgr.ExpeditionMgr.SetStageState(msg.stageId+1,0)
        logicMgr.ExpeditionMgr.SetCurStageId(math.min(msg.stageId+1,12))
        logicMgr.ExpeditionMgr.AddShowBuff(msg.buffId)
        FireEvent(Config.EventType.ExpeditionGetRewardSuc,msg.stageId)
    end
end

function t.ResExpeditionPartnerInfoHandler(msg)
    for k,v in pairs(msg.partnerList) do
        logicMgr.ExpeditionMgr.AddHeroList(v)
    end
end


function t.ResUseBuffHandler(msg)
    local mgr = logicMgr.ExpeditionMgr

    if msg.useBuffId > 0 then
        mgr.AddStageBuff(msg.useBuffId)

        local buff_list = logicMgr.ExpeditionMgr.GetCurStageCfgParam(mgr.GetCurStageId() - 1, "f_Buff_3")
        if buff_list then
            local buff_cfg = nil
            for k,v in pairs(buff_list) do
                if v[1] == msg.useBuffId then
                    buff_cfg = v
                    break
                end
            end

            -- local _buffDic = {buff_id = tostring(msg.useBuffId)}--埋点记录
            -- if buff_cfg then
            --     _buffDic.action_object = tostring(buff_cfg[3])
            -- end
            
            -- TAManager.TrackByDictionary("expedition_choose_card_buff", _buffDic)
        end
    end
    mgr.ClearShowBuff()
    FireEvent(Config.EventType.ExpeditionUseBuffSuc)
end

function t.ResExpeditionBossHandler(msg)
    logicMgr.ExpeditionMgr.ClearSelectAwardIndex()

    if msg.state ~= 0 then
        logError("进入战斗错误-战斗返回失败 code:"..msg.state)
        FireEvent(Config.EventType.LoadingCancelByFightError,"战斗返回失败")
        return
    end
    if logicMgr.ExpeditionMgr.GetCurStageId() == ExpeditionMgr.MAX_LEVEL then
        ExpeditionMgr.needShowLastTip = true
    end
    FightManager.InitRewards(msg.items)
    logicMgr.ExpeditionMgr.SetWard(msg.areaItems)
    BattlePlaybackManager.RequestReport(msg.fightId,msg.fightResult,msg.record)
    logicMgr.ExpeditionMgr.SetCanSweep(false);
    --[[BattlePlaybackManager.setBattleRecord(msg.record)
    BattlePlaybackManager.setBattleResult(msg.fightResult)
    -- 请求战斗命令，然后回放战斗
    BattlePlaybackManager.requestFightCmdThenPlay(msg.record, EnumConst.FightTypeConst.Expedition)]]
end

function t.ResExpeditionSweepHandler(msg)
    if msg.state == 0 then
        logicMgr.ExpeditionMgr.SetCanSweep(false)
        t.ReqSelectRegion(logicMgr.ExpeditionMgr.mapId)
        showUI(PanelNames.UICommonItemGet,nil,nil,2,msg.items,nil,getLanguage("expedition__mopp_up_des5"),nil,nil,nil,nil,6);
    end
end

function t.ResExpeditionQuickSweepHandler(msg)
    if msg.state == 0 then
        local cost = tonumber(G.dataTable["t_global"][tostring(595)]["f_string_value"][3])
        logicMgr.ExpeditionMgr.ReduceStrength(cost)
        logicMgr.ExpeditionMgr.SetCanSweep(false)
        --t.ReqSelectRegion(logicMgr.ExpeditionMgr.mapId)
        showUI(PanelNames.UICommonItemGet,nil,nil,2,msg.items,nil,getLanguage("expedition__mopp_up_des8"),nil,nil,nil,nil,6);
        FireEvent(Config.EventType.Fresh_ExpeditionStrength)
    end
end

--使用道具增加体力时，服务器的推送
function t.PushExpeditionPower(msg)
    if msg.state == 0 then
        if logicMgr.ExpeditionMgr.strength < logicMgr.ExpeditionMgr.GetFullEnergy() and msg.power >= logicMgr.ExpeditionMgr.GetFullEnergy() then
            local perStrengthCostSec = 0    --每回复一点体力值，需要的时间
            local cfgInfo = G.dataTable["t_global"][tostring(595)]["f_string_value"]
            if cfgInfo and cfgInfo[2] and tonumber(cfgInfo[2]) > 0 then
                perStrengthCostSec = tonumber(cfgInfo[2])
            end
            logicMgr.ExpeditionMgr.srvCDTime = perStrengthCostSec - (logicMgr.ExpeditionMgr.nextStrengthAddTime - HelperFunc.GetServerTime())
            logicMgr.ExpeditionMgr.nextStrengthAddTime = 0
        end
        logicMgr.ExpeditionMgr.strength = msg.power
        FireEvent(Config.EventType.Fresh_ExpeditionStrength)
		FireEvent(Config.EventType.ExpeditionSweepRefresh)
    end
end

--endregion res